package com.limou.runner;

import com.limou.domain.entity.Article;
import com.limou.mapper.ArticleMapper;
import com.limou.utils.RedisCache;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.boot.CommandLineRunner;
import org.springframework.stereotype.Component;

import java.util.List;
import java.util.Map;
import java.util.stream.Collectors;

/**
 * ①在应用启动时把博客的浏览量存储到redis中
 * ②更新浏览量时去更新redis中的数据
 * ③每隔10分钟把Redis中的浏览量更新到数据库中
 * ④读取文章浏览量时从redis读取
 */
@Component
public class ViewCountRunner implements CommandLineRunner {
    @Autowired
    private ArticleMapper articleMapper;
    @Autowired
    private RedisCache redisCache;

    @Override
    public void run(String... args) throws Exception {
        //查询博客信息 id viewCount
        List<Article> articles = articleMapper.selectList(null);
        Map<String, Integer> viewCountMap = articles.stream()
                .collect(Collectors.toMap(article -> article.getId().toString(),
                        article -> {
                            return article.getViewCount().intValue();//
                        }));
        //存储到redis中
        redisCache.setCacheMap("article:viewCount", viewCountMap);
    }
}